<template>
    <div><!-- 添加或修改物模型模板对话框 -->
        <el-dialog draggable :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
            <el-form ref="thingsModelFormRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="模型id" prop="modelId" v-show="false">
                    <el-input v-model="form.modelId" />
                </el-form-item>
                <el-form-item label="模型名称" prop="templateName">
                    <el-input v-model="form.modelName" placeholder="请输入物模型名称,例如：温度" />
                </el-form-item>
                <el-form-item label="模型标识" prop="identifier">
                    <el-input v-model="form.identifier" placeholder="请输入模型标识符,例如：temperature" />
                </el-form-item>
                <el-form-item label="模型类别" prop="type">
                    <el-radio-group v-model="form.type" size="large" fill="#6cf">
                        <el-radio-button label="属性" :value=1 />
                        <el-radio-button label="功能" :value=2 />
                        <el-radio-button label="事件" :value=3 />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="模型特征" prop="templateType">
                    <el-checkbox v-model="form.isChart" label="图标展示" :true-value="1" :false-value="0"
                        :disabled="form.type !== 1" v-show="form.type === 1" />
                    <el-checkbox v-model="form.isMonitor" label="实时监测" :true-value="1" :false-value="0"
                        :disabled="form.type !== 1" v-show="form.type === 1" />
                    <el-checkbox v-model="form.isReadonly" label="只读数据" :true-value="1" :false-value="0" />
                    <el-checkbox v-model="form.isHistory" label="历史存储" :true-value="1" :false-value="0" />
                    <el-checkbox v-model="form.isSharePerm" label="分享权限" :true-value="1" :false-value="0" />
                </el-form-item>
                <el-form-item v-model="form.datatype" label="数据类型" prop="dataType">
                    <el-select v-model="form.datatype" placeholder="请选择数据类型">
                        <el-option v-for="dict in iot_data_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" :disabled="form.type == 1 && dict.value != 1 && dict.value != 2" />

                    </el-select>
                </el-form-item>
                <el-form-item v-if="form.datatype == '1' || form.datatype == '2'" label="取值范围" prop="minToMax">
                    <el-input-number v-model="specs.min" />
                    <span style="margin: 0 10px;">到</span>
                    <el-input-number v-model="specs.max" />
                </el-form-item>
                <el-form-item label="单位" prop="unit" v-if="form.datatype == '1' || form.datatype == '2'">
                    <el-input v-model="specs.unit" placeholder="请输入单位,例如：℃" />
                </el-form-item>
                <el-form-item label="步长" prop="step" v-if="form.datatype == '1' || form.datatype == '2'">
                    <el-input v-model="specs.step" placeholder="请输入步长" />
                </el-form-item>
                <div v-if="form.datatype == '4'">
                    <el-form-item label="布尔值" prop="">
                        <el-row style="margin-bottom: 10px">
                            <el-col :span="9">
                                <el-input v-model="specs.falseText" placeholder="例如：关闭" />
                            </el-col>
                            <el-col :span="10" :offset="1">（0 值对应文本）</el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="9">
                                <el-input v-model="specs.trueText" placeholder="例如：打开" />
                            </el-col>
                            <el-col :span="10" :offset="1">（1 值对应文本）</el-col>
                        </el-row>
                    </el-form-item>
                </div>
                <div v-if="form.datatype == '6'">
                    <el-form-item label="展示方式">
                        <el-select v-model="specs.showWay" placeholder="请选择展示方式" style="width: 175px">
                            <el-option key="select" label="下拉框" value="select"></el-option>
                            <el-option key="button" label="按钮" value="button"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="枚举项" prop="">
                        <el-row v-for="(item, index) in specs.enumList" :key="'enum' + index"
                            style="margin-bottom: 10px">
                            <el-col :span="9">
                                <el-input v-model="item.value" placeholder="参数值，例如：0" />
                            </el-col>
                            <el-col :span="11" :offset="1">
                                <el-input v-model="item.text" placeholder="参数描述，例如：中速档位" />
                            </el-col>
                            <el-col :span="2" :offset="1" v-if="index != 0"><a style="color: #f56c6c"
                                    @click="removeEnumItem(index)">删除</a></el-col>
                        </el-row>
                        <div>
                            +
                            <a style="color: #409eff" @click="addEnumItem()">添加枚举项</a>
                        </div>
                    </el-form-item>
                </div>
                <div v-if="form.datatype == '3'">
                    <el-form-item label="最大长度" prop="">
                        <el-row>
                            <el-col :span="9">
                                <el-input v-model="specs.maxLength" placeholder="例如：1024" type="number" />
                            </el-col>
                            <el-col :span="14" :offset="1">（字符串的最大长度）</el-col>
                        </el-row>
                    </el-form-item>
                </div>
                <div v-if="form.datatype == '5'">
                    <el-form-item label="元素个数" prop="">
                        <el-row>
                            <el-col :span="9">
                                <el-input v-model="specs.arrayCount" placeholder="例如：5" type="number" />
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <el-form-item label="数组类型" prop="">
                        <el-radio-group v-model="specs.arrayType">
                            <el-radio label="1">整数</el-radio>
                            <el-radio label="2">小数</el-radio>
                            <el-radio label="3">字符串</el-radio>
                            <el-radio label="7">对象</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="对象参数" v-if="specs.arrayType == 7">
                        <div style="background-color: #f8f8f8; border-radius: 5px">
                            <el-row style="padding: 0 10px 5px" v-for="(item, index) in specs.params" :key="index">
                                <div style="margin-top: 5px" v-if="index == 0"></div>
                                <el-col :span="18">
                                    <el-input readonly v-model="item.name" size="small" placeholder="请选择设备"
                                        style="margin-top: 3px">
                                        <template slot="prepend">
                                            <el-tag size="small" effect="dark"
                                                style="margin-left: -21px; height: 26px; line-height: 26px">{{
                                                    item.order }}</el-tag>
                                            {{ form.identifier + '_' + item.id }}
                                        </template>
                                        <el-button slot="append" @click="editParameter(item, index)"
                                            size="small">编辑</el-button>
                                    </el-input>
                                </el-col>
                                <el-col :span="2" :offset="2">
                                    <el-button size="small" plain type="danger" style="padding: 5px"
                                        icon="el-icon-delete" @click="removeParameter(index)">删除</el-button>
                                </el-col>
                            </el-row>
                        </div>
                        <div>
                            +
                            <a style="color: #409eff" @click="addParameter()">添加参数</a>
                        </div>
                    </el-form-item>
                </div>
                <div v-if="form.datatype == '7'">
                    <el-form-item label="对象参数" prop="">
                        <div style="background-color: #f8f8f8; border-radius: 5px">
                            <el-row style="padding: 0 10px 5px" v-for="(item, index) in specs.params" :key="index">
                                <div style="margin-top: 5px" v-if="index == 0"></div>
                                <el-col :span="18">
                                    <el-input readonly v-model="item.templateName" size="small" placeholder="请选择设备"
                                        style="margin-top: 3px">
                                        <template #prepend>
                                            <el-tag size="small" effect="dark"
                                                style="margin-left: -21px; height: 26px; line-height: 26px">{{
                                                    item.modelOrder }}</el-tag>
                                            {{ form.identifier + '_' + item.identifier }}
                                        </template>
                                        <template #append>
                                            <el-button @click="editParameter(item, index)">编辑</el-button>
                                        </template>
                                    </el-input>
                                </el-col>
                                <el-col :span="2" :offset="2">
                                    <el-button size="default" plain type="danger" style="margin-top: 5px;" icon="delete"
                                        @click="removeParameter(index)">删除</el-button>
                                </el-col>
                            </el-row>
                        </div>
                        <div>
                            +
                            <a style="color: #409eff" @click="addParameter()">添加参数</a>
                        </div>
                    </el-form-item>
                </div>

                <el-form-item label=" 排序" prop="modelOrder">
                    <el-input-number v-model="form.modelOrder" :min="1" :max="99999" placeholder="请输入排序，值越大，排序越靠前"
                        :style="{ width: '300px' }" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <para-meter ref="paraMeter"></para-meter>
    </div>
</template>
<script setup lang="ts">
import { specs, ThingsModelVO, ThingsModelQuery, ThingsModelForm } from '@/api/iot/thingsModel/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_type, iot_data_type, iot_yes_no } = toRefs<any>(proxy?.useDict('iot_data_type', 'iot_type', 'iot_yes_no'));
import { listThingsModel, getThingsModel, delThingsModel, addThingsModel, updateThingsModel } from '@/api/iot/thingsModel';
import ParaMeter from '../thingsModelTemplate/parameter.vue';
const paraMeter = ref<InstanceType<typeof ParaMeter> | null>(null)
const thingsModelList = ref<ThingsModelVO[]>([]);
const loading = ref(true);
const total = ref(0);
const buttonLoading = ref(false);
const thingsModelFormRef = ref<ElFormInstance>();
const productIdAdd = inject<string>('productIdAdd')
const productNameAdd = inject<string>('productNameAdd')
const openType = ref('');
const modelId = ref(undefined);
const specs: specs = reactive({
    min: 0,
    max: 0,
    unit: '',
    step: undefined,
    type: undefined,
    falseText: '',
    trueText: '',
    showWay: 'select',
    maxLength: '1024',
    arrayCount: 5,
    arrayType: 1,
    params: [],
    enumList: [{ value: undefined, text: undefined }]
});
const initFormData: ThingsModelForm = {
    modelId: undefined,
    modelName: undefined,
    productId: productIdAdd,
    productName: productNameAdd,
    identifier: undefined,
    type: 1,
    datatype: '1',
    specs: undefined,
    isChart: 1,
    isMonitor: 1,
    isHistory: 1,
    isReadonly: 1,
    isSharePerm: 1,
    modelOrder: undefined,
}
const data = reactive<PageData<ThingsModelForm, ThingsModelQuery>>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10
    },
    rules: {
        modelId: [
            { required: true, message: "物模型ID不能为空", trigger: "blur" }
        ],
        modelName: [
            { required: true, message: "物模型名称不能为空", trigger: "blur" }
        ],
        identifier: [
            { required: true, message: "标识符，产品下唯一不能为空", trigger: "blur" }
        ],
        type: [
            { required: true, message: "模型类别不能为空", trigger: "change" }
        ],
        datatype: [
            { required: true, message: "数据类型不能为空", trigger: "change" }
        ],
        isChart: [
            { required: true, message: "是否图表展示不能为空", trigger: "blur" }
        ],
        isMonitor: [
            { required: true, message: "是否实时监测不能为空", trigger: "blur" }
        ],
        isHistory: [
            { required: true, message: "是否历史存储 (0-否，1-是）不能为空", trigger: "blur" }
        ],
    }
});

const { queryParams, form, rules } = toRefs(data);
watch(() => form.value.type, (newType) => {
    switch (newType) {
        case 1: // 属性
            form.value.isChart = 1;
            form.value.isMonitor = 1;
            form.value.isReadonly = 1;
            form.value.isHistory = 1;
            form.value.isSharePerm = 1;
            break;
        case 2: // 功能
            form.value.isChart = 0;
            form.value.isMonitor = 0;
            form.value.isReadonly = 0;
            form.value.isHistory = 1;
            form.value.isSharePerm = 1;
            break;
        case 3: // 事件
            form.value.isChart = 0;
            form.value.isMonitor = 0;
            form.value.isReadonly = 1;
            form.value.isHistory = 1;
            form.value.isSharePerm = 0;
            break;
    }
});

onMounted(() => {
    console.log("==========" + queryParams.value)
    console.log(queryParams.value)
    // getList();
    reset();

});


const getThingsModelById = async (modelId: string | number) => {
    console.log("==========" + modelId)
    const res = await getThingsModel(modelId);
    Object.assign(form.value, res.data);

    // 把res.data.specs字符串转为对象
    if (typeof res.data.specs === 'string') {
        const parsedSpecs = JSON.parse(res.data.specs);
        Object.assign(specs, parsedSpecs);
    }

}



/** 查询物模型列表 */
const getList = async () => {
    loading.value = true;
    const res = await listThingsModel(queryParams.value);
    thingsModelList.value = res.rows;
    total.value = res.total;
    loading.value = false;
}
/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    specs.min = 0;
    specs.max = 0;
    specs.unit = '';
    specs.step = undefined;
    specs.type = undefined;
    specs.falseText = '';
    specs.trueText = '';
    specs.showWay = 'select';
    specs.maxLength = '1024';
    specs.arrayCount = 5;
    specs.arrayType = 1;
    specs.params = [];
    specs.enumList = [{ value: undefined, text: undefined }]
    thingsModelFormRef.value?.resetFields();
}
/** 取消按钮 */
const cancel = () => {
    reset();

    dialog.visible = false;
}
// 对象类型参数
const paramData = ref({
    index: -1,
    parameter: {},
})
/** 编辑参数*/
const editParameter = (data, index) => {

    paramData.value = {
        index: index,
        parameter: data,
    };
}

/** 删除动作 */
const removeParameter = (index) => {
    specs.params.splice(index, 1);
}

/** 添加参数 */
const addParameter = () => {
    if (paraMeter.value) {
        paraMeter.value.dialog1.visible = true;
    } else {
        console.error('paraMeter is not ready');
    }

}
// 子组件
const props = defineProps<{
    getList: () => void
}>()


/** 提交按钮 */
const submitForm = () => {
    console.log("form=========");
    console.log(productIdAdd);
    console.log(productNameAdd);
    console.log(thingsModelFormRef.value)
    thingsModelFormRef.value?.validate(async (valid: boolean) => {
        console.log("===" + valid)
        if (valid) {
            buttonLoading.value = true;
            form.value.specs = JSON.stringify(specs);
            if (form.value.modelId) {
                await updateThingsModel(form.value).finally(() => buttonLoading.value = false);
            } else {
                console.log(form.value)
                await addThingsModel(form.value).finally(() => buttonLoading.value = false);
            }
            proxy?.$modal.msgSuccess("操作成功");
            dialog.visible = false;
            // 调用父组件方法
            props.getList()
            reset();
        }
    });
}
/** 添加枚举项 */
const addEnumItem = () => {
    specs.enumList.push({
        value: '',
        text: '',
    });
}
/** 删除枚举项 */
const removeEnumItem = (index) => {
    specs.enumList.splice(index, 1);
}

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});
defineExpose({
    dialog,
    openType,
    modelId,
    getThingsModelById
})

</script>
<style scoped></style>